<script setup lang="ts">
defineOptions({name: 'MenuCreate'})
import {getIsMobile, delObjEmptyVal, makeTree} from "@/utils/helper"
import {useI18n} from "vue-i18n"
import {createMenu, getMenuList} from '@/api/menu'

const dataId = ref<number | string | undefined>(0)
const formRef = ref()
const visible = ref<boolean>(false)
const disabledSubmit = ref<boolean>(false)
const isMobile = getIsMobile()
const {t} = useI18n()
const formItems = ref<any>([
	{
		key: 'pid', type: 'treeselect',
		props: {data: [], checkStrictly: true, placeholder: t('common.selectPlaceholder'), clearable: true}
	},
	{key: 'name', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'title', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'route', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'path', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'activePath', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'link', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'icon', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'permissionMark', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'queryParams', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'pathParams', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'badgeText', type: 'input', placeholder: t('common.inputPlaceholder'), clearable: true},
	{key: 'method', type: 'select', placeholder: t('common.selectPlaceholder'), clearable: true},
	{
		label: t('common.field.sort'), key: 'sort', type: 'input', clearable: true,
		placeholder: t('common.inputPlaceholder') + t('common.field.sort')
	},
	{key: 'belongTo', type: 'radiogroup'},
	{key: 'status', type: 'radiogroup'},
	{key: 'type', type: 'radiogroup'},
	{key: 'isHide', type: 'radiogroup'},
	{key: 'isHideTab', type: 'radiogroup'},
	{key: 'isKeepAlive', type: 'radiogroup'},
	{key: 'isFixedTab', type: 'radiogroup'},
	{key: 'isIframe', type: 'radiogroup'},
	{key: 'isFullPage', type: 'radiogroup'},
	{key: 'isBadge', type: 'radiogroup'},
])

const checkJson = (rule: any, value: any, callback: any) => {
	if (value) {
		try {
			JSON.parse(value)
		} catch (e) {
			callback(rule.message)
		}
	}
	callback()
}

const formRules = {
	belongTo: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	name: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	title: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	permissionMark: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	sort: [{required: true, message: t('formRule.required'), trigger: 'blur'},],
	method: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	status: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	type: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isHide: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isHideTab: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isKeepAlive: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isFixedTab: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isIframe: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isFullPage: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	isBadge: [{required: true, message: t('formRule.required'), trigger: 'blur'}],
	queryParams: [{validator: checkJson, message: t('formRule.checkJson'), trigger: 'change'}],
	pathParams: [{validator: checkJson, message: t('formRule.checkJson'), trigger: 'change'}]
}

const formData = ref<any>({
	pid: undefined, belongTo: 1, name: undefined, title: undefined, route: undefined, path: undefined,
	activePath: undefined, link: undefined, icon: undefined, permissionMark: undefined, queryParams: undefined,
	pathParams: undefined, method: 1, status: 1, type: 1, isHide: 2, isHideTab: 2, isKeepAlive: 2, isFixedTab: 2,
	isIframe: 2, isFullPage: 2, isBadge: 2, badgeText: undefined, sort: 1000
})

interface emits {
	(e: 'success', params: Record<string, any>): void
}

interface Props {
	enumData?: Record<string, any>
	languageData?: Record<string, any>
}

const props = defineProps<Props>()
const emit = defineEmits<emits>()

const handleSubmit = async () => {
	await formRef.value.validate()
	if (disabledSubmit.value) return false
	disabledSubmit.value = true
	try {
		const sendData = {...formData.value}
		delObjEmptyVal(sendData)
		const res = await createMenu(sendData)
		emit('success', res)
		setTimeout(() => {
			close()
		}, 600)
	} catch (error) {
		console.error('[MenuCreate] Unexpected error:', error)
	} finally {
		setTimeout(() => {
			disabledSubmit.value = false
		}, 800);
	}
}

const getData = async () => {
	const getMenuRes: any = await getMenuList({page: 1, limit: 1000, fields: ['menuId', 'title', 'pid']})
	const temp: any = []
	getMenuRes.list.forEach((item: any) => {
		temp.push({
			label: t(item.title),
			value: item.menuId,
			pid: item.pid
		})
	})
	formItems.value[0].props.data = makeTree(temp, 'value', 'pid', 0)
}

watch(() => props.enumData, (newVal: any) => {
	if (newVal.menu) {
		formItems.value.forEach((item: any, index: any) => {
			if (newVal.menu[item.key]) {
				formItems.value[index].options = newVal.menu[item.key]
			}
		})
	}
}, {immediate: true});

watch(() => props.languageData, (newVal: any) => {
	if (newVal.menu) {
		formItems.value.forEach((item: any, index: any) => {
			if (!item.label && newVal.menu.field[item.key]) {
				formItems.value[index].label = newVal.menu.field[item.key]
				if (item.placeholder) {
					formItems.value[index].placeholder = item.placeholder + newVal.menu.field[item.key]
				}
				if (item?.props?.placeholder) {
					formItems.value[index].props.placeholder = item.props.placeholder + newVal.menu.field[item.key]
				}
			}
		})
	}
}, {immediate: true});

const open = (id?: number) => {
	visible.value = true
	dataId.value = id
	Object.assign(formData.value, {pid: id})
	getData()
}

const close = () => {
	formRef.value.reset()
	visible.value = false
}

defineExpose({open, close})
</script>

<template>
	<div class="form-operate-box">
		<ElDrawer v-model="visible" :size="isMobile ? '100%' : '80%'" :title="t('common.create')"
			  :close-on-click-modal="false" @close="close">
			<ArtForm ref="formRef" labelPosition="top" v-model="formData" :items="formItems"
				 :rules="formRules" :disabledSubmit="disabledSubmit" :showReset="false"
				 @close="close" @submit="handleSubmit"/>
		</ElDrawer>
	</div>
</template>

<style scoped lang="scss">
.form-operate-box {
	:deep(.el-form-item--label-top .el-form-item__label) {
		margin-left: 3px !important;
		margin-bottom: 2px !important;
	}

	:deep(.el-drawer__header) {
		margin-bottom: 20px;
	}

	:deep(.el-drawer__title) {
		text-align: center;
	}

	:deep(.el-drawer__body) {
		padding-top: 0;
	}

	:deep(.action-buttons-wrapper) {
		margin-top: 8px !important;
		justify-content: flex-end !important;
	}
}
</style>